<?php namespace Common\Model;
use Hdphp\Model\Model;

class Goods extends Model{
	protected $table="goods";
	//自动验证
	protected $validate=array(
		//array(字段名，验证方法，错误信息，验证条件，验证时间)
		array('gname','required','商品名称不能为空',3,3),
		array('gname','required','商品名称不能为空',3,3),
		array('shopprice','required','商品价不能为空',3,3)
	);
	//自动完成
	protected $auto=array(
		//array(字段名，处理方法，方法类型，验证时间)
		array('time','time','function',3,1),
		array('Admin_aid','getAid','method',3,1),
		array('gnumber','time','function',3,1),
	);
	//通过session获取用户ID
	public function getAid(){
//		P($_SESSION);
		return $_SESSION['info']['aid'];
	}

	//添加商品
	public function store(){
		if($this->create()){
		//获得分类
		$cid=Q('post.category_cid');
		$cateModel=new \Common\Model\Cate;
		$cateData=$cateModel->where("cid={$cid}")->pluck('type_tid');
//		p($cateData);die;
		//没有类型ID，要压入类型ID
		$this->data['type_tid']=$cateData;
		$gid=$this->add();
		
		//获得商品表的自增ID
		$goodsDetail=new \Common\Model\GoodsDetail;
		$goodsDetail->create();
		$pic=Q('post.picintro');
		$pic=implode(',',$pic);
		$goodsDetail->data['picintro']=$pic;
		$goodsDetail->data['goods_gid']=$gid;
		$goodsDetail->add();	
		$goodsAttrModel = new \Common\Model\GoodsAttr;
		
		//属性添加
		foreach (Q('post.attr') as $taid => $v) {
			if($v){
				$data = array(
					'gavalue'=>$v,
					'type_attr_taid'=>$taid,
					'goods_gid'=>$gid
				);
				$goodsAttrModel->add($data);
			}
		}
		//规格添加
		$spec = Q('post.spec');
		if($spec){
			$value = $spec['value'];
			foreach ($value as $taid => $v) {
				foreach ($v as $kk => $vv) {
					$data = array(
						'gavalue'=>$vv,
						'type_attr_taid'=>$taid,
						'goods_gid'=>$gid,
						'added'=>$spec['added'][$taid][$kk]
					);
					$goodsAttrModel->add($data);
				}
			}
		}
			return true;
		}
		return false;
	}
	

	//编辑
	public function edit(){
		if(!$this->create()){
			return false;
		}
			$this->save();
			return true;
	}
	
}
?>